package com.volunteer.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.volunteer.common.BusinessException;
import com.volunteer.common.ResultCode;
import com.volunteer.entity.Activity;
import com.volunteer.entity.ActivityType;
import com.volunteer.entity.UserCollection;
import com.volunteer.entity.Registration;
import com.volunteer.mapper.*;
import com.volunteer.model.vo.ActivityDetailVO;
import com.volunteer.model.vo.ActivityListVO;
import com.volunteer.model.vo.HomeDataVO;
import com.volunteer.service.ActivityService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 活动服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {

    private final ActivityMapper activityMapper;
    private final CollectionMapper collectionMapper;
    private final RegistrationMapper registrationMapper;
    private final ActivityTypeMapper activityTypeMapper;

    /**
     * 创建活动
     *
     * @param activity 活动信息
     * @return 是否成功
     */
    @Override
    public boolean createActivity(Activity activity) {
        if (activity == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR);
        }

        // 校验必填字段
        if (StrUtil.isBlank(activity.getTitle()) || activity.getStartTime() == null || activity.getEndTime() == null || activity.getRegisterStartTime() == null || activity.getRegisterEndTime() == null || activity.getRecruitNumber() == null || activity.getCreatorId() == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR);
        }

        // 校验时间
        LocalDateTime now = LocalDateTime.now();
        if (activity.getStartTime().isBefore(now) || activity.getEndTime().isBefore(activity.getStartTime()) || activity.getRegisterEndTime().isBefore(activity.getRegisterStartTime()) || activity.getRegisterEndTime().isAfter(activity.getStartTime())) {
            throw new BusinessException("活动时间设置有误");
        }

        // 设置默认值
        activity.setRegisteredNumber(0);
        activity.setStatus(0); // 未开始
        activity.setIsRecommended(0); // 不推荐
        activity.setIsDisplay(1); // 默认展示
        activity.setCreateTime(now);
        activity.setUpdateTime(now);
        return this.save(activity);
    }

    /**
     * 更新活动信息
     *
     * @param activity 活动信息
     * @return 是否成功
     */
    @Override
    public boolean updateActivity(Activity activity) {
        if (activity == null || activity.getId() == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR);
        }

        // 检查活动是否存在
        Activity existActivity = this.getById(activity.getId());
        if (existActivity == null) {
            throw new BusinessException(ResultCode.NOT_FOUND);
        }

        // 检查权限
        Long userId = StpUtil.getLoginIdAsLong();
        if (!existActivity.getCreatorId().equals(userId) && StpUtil.getRoleList().stream().noneMatch(r -> r.equals("admin"))) {
            throw new BusinessException(ResultCode.FORBIDDEN);
        }

        // 不能修改已结束或已取消的活动
        if (existActivity.getStatus() == 3 || existActivity.getStatus() == 4) {
            throw new BusinessException("已结束或已取消的活动不能修改");
        }

        // 不允许修改的字段
        activity.setRegisteredNumber(existActivity.getRegisteredNumber());
        activity.setStatus(existActivity.getStatus());
        activity.setCreatorId(existActivity.getCreatorId());
        activity.setCreateTime(existActivity.getCreateTime());
        activity.setUpdateTime(LocalDateTime.now());

        return this.updateById(activity);
    }

    /**
     * 取消活动
     *
     * @param activityId 活动ID
     * @param userId     操作用户ID
     * @return 是否成功
     */
    @Override
    public boolean cancelActivity(Long activityId, Long userId) {
        if (activityId == null || userId == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR);
        }

        // 检查活动是否存在
        Activity activity = this.getById(activityId);
        if (activity == null) {
            throw new BusinessException(ResultCode.NOT_FOUND);
        }

        // 检查权限
        if (!activity.getCreatorId().equals(userId) && StpUtil.getRoleList().stream().noneMatch(r -> r.equals("admin"))) {
            throw new BusinessException(ResultCode.FORBIDDEN);
        }

        // 已结束的活动不能取消
        if (activity.getStatus() == 3) {
            throw new BusinessException("已结束的活动不能取消");
        }

        // 已取消的活动不能重复取消
        if (activity.getStatus() == 4) {
            throw new BusinessException("活动已取消");
        }

        // 更新活动状态
        activity.setStatus(4); // 已取消
        activity.setUpdateTime(LocalDateTime.now());

        return this.updateById(activity);
    }

    /**
     * 分页查询公开活动列表
     *
     * @param page     分页参数
     * @param activity 查询条件
     * @return 活动列表
     */
    @Override
    public Page<Activity> pagePublicActivities(Page<Activity> page, Activity activity) {
        LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();

        // 只查询展示的活动
        queryWrapper.eq(Activity::getIsDisplay, 1);

        // 不查询已取消的活动
        queryWrapper.ne(Activity::getStatus, 4);

        List<ActivityType> activityTypes = activityTypeMapper.selectList(null);
        Map<Long, String> map = activityTypes.stream().collect(Collectors.toMap(ActivityType::getId, ActivityType::getName));

        if (activity != null) {
            // 按标题查询
            if (StrUtil.isNotBlank(activity.getTitle())) {
                queryWrapper.like(Activity::getTitle, activity.getTitle());
            }

            // 按状态查询
            if (activity.getStatus() != null) {
                queryWrapper.eq(Activity::getStatus, activity.getStatus());
            }

            // 按团队查询
            if (StrUtil.isNotBlank(activity.getTeam())) {
                queryWrapper.like(Activity::getTeam, activity.getTeam());
            }

            // 按是否推荐查询
            if (activity.getIsRecommended() != null) {
                queryWrapper.eq(Activity::getIsRecommended, activity.getIsRecommended());
            }
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(Activity::getCreateTime);
        Page<Activity> activityPage = this.page(page, queryWrapper);
        List<Activity> list = activityPage.getRecords().stream().peek(activity1 -> {
            activity1.setActivityTypeName(map.get(activity1.getActivityTypeId()));
        }).collect(Collectors.toList());
        activityPage.setRecords(list);
        return activityPage;
    }

    /**
     * 分页查询用户创建的活动列表
     *
     * @param page     分页参数
     * @param userId   用户ID
     * @param activity 查询条件
     * @return 活动列表
     */
    @Override
    public Page<Activity> pageUserCreateActivities(Page<Activity> page, Long userId, Activity activity) {
        if (userId == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR);
        }

        LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();

        // 查询用户创建的活动
        queryWrapper.eq(Activity::getCreatorId, userId);

        if (activity != null) {
            // 按标题查询
            if (StrUtil.isNotBlank(activity.getTitle())) {
                queryWrapper.like(Activity::getTitle, activity.getTitle());
            }

            // 按状态查询
            if (activity.getStatus() != null) {
                queryWrapper.eq(Activity::getStatus, activity.getStatus());
            }
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(Activity::getCreateTime);

        return this.page(page, queryWrapper);
    }

    /**
     * 分页查询用户报名的活动列表
     *
     * @param page     分页参数
     * @param userId   用户ID
     * @param activity 查询条件
     * @return 活动列表
     */
    @Override
    public Page<Activity> pageUserJoinActivities(Page<Activity> page, Long userId, Activity activity) {
        if (userId == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR);
        }

        // 查询用户报名的活动ID列表
        LambdaQueryWrapper<Registration> registrationQueryWrapper = new LambdaQueryWrapper<>();
        registrationQueryWrapper.eq(Registration::getUserId, userId);

        // 只查询未取消的报名
        registrationQueryWrapper.ne(Registration::getStatus, 3);

        List<Registration> registrations = registrationMapper.selectList(registrationQueryWrapper);
        if (registrations.isEmpty()) {
            return new Page<>(page.getCurrent(), page.getSize());
        }

        List<Long> activityIds = registrations.stream().map(Registration::getActivityId).collect(Collectors.toList());

        // 查询活动列表
        LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Activity::getId, activityIds);

        if (activity != null) {
            // 按标题查询
            if (StrUtil.isNotBlank(activity.getTitle())) {
                queryWrapper.like(Activity::getTitle, activity.getTitle());
            }

            // 按状态查询
            if (activity.getStatus() != null) {
                queryWrapper.eq(Activity::getStatus, activity.getStatus());
            }
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(Activity::getCreateTime);

        return this.page(page, queryWrapper);
    }

    /**
     * 分页查询用户收藏的活动列表
     *
     * @param page     分页参数
     * @param userId   用户ID
     * @param activity 查询条件
     * @return 活动列表
     */
    @Override
    public Page<Activity> pageUserCollectActivities(Page<Activity> page, Long userId, Activity activity) {
        if (userId == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR);
        }

        // 查询用户收藏的活动ID列表
        LambdaQueryWrapper<UserCollection> collectionQueryWrapper = new LambdaQueryWrapper<>();
        collectionQueryWrapper.eq(UserCollection::getUserId, userId);
        List<UserCollection> userCollections = collectionMapper.selectList(collectionQueryWrapper);

        if (userCollections.isEmpty()) {
            return new Page<>(page.getCurrent(), page.getSize());
        }

        List<Long> activityIds = userCollections.stream().map(UserCollection::getActivityId).collect(Collectors.toList());

        // 查询活动列表
        LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Activity::getId, activityIds);

        // 只查询展示的活动
        queryWrapper.eq(Activity::getIsDisplay, 1);

        // 不查询已取消的活动
        queryWrapper.ne(Activity::getStatus, 4);

        if (activity != null) {
            // 按标题查询
            if (StrUtil.isNotBlank(activity.getTitle())) {
                queryWrapper.like(Activity::getTitle, activity.getTitle());
            }

            // 按状态查询
            if (activity.getStatus() != null) {
                queryWrapper.eq(Activity::getStatus, activity.getStatus());
            }
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(Activity::getCreateTime);

        return this.page(page, queryWrapper);
    }

    /**
     * 设置活动是否推荐
     *
     * @param activityId    活动ID
     * @param isRecommended 是否推荐（0-否 1-是）
     * @return 是否成功
     */
    @Override
    public boolean setActivityRecommend(Long activityId, Integer isRecommended) {
        if (activityId == null || isRecommended == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR);
        }

        // 检查活动是否存在
        Activity activity = this.getById(activityId);
        if (activity == null) {
            throw new BusinessException(ResultCode.NOT_FOUND);
        }

        // 更新是否推荐
        activity.setIsRecommended(isRecommended);
        activity.setUpdateTime(LocalDateTime.now());

        return this.updateById(activity);
    }

    /**
     * 设置活动是否展示
     *
     * @param activityId 活动ID
     * @param isDisplay  是否展示（0-否 1-是）
     * @return 是否成功
     */
    @Override
    public boolean setActivityDisplay(Long activityId, Integer isDisplay) {
        if (activityId == null || isDisplay == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR);
        }

        // 检查活动是否存在
        Activity activity = this.getById(activityId);
        if (activity == null) {
            throw new BusinessException(ResultCode.NOT_FOUND);
        }

        // 更新是否展示
        activity.setIsDisplay(isDisplay);
        activity.setUpdateTime(LocalDateTime.now());

        return this.updateById(activity);
    }

    @Override
    public List<HomeDataVO.ActivityVO> getHotActivities() {
        List<Activity> activities = this.list(new LambdaQueryWrapper<Activity>().eq(Activity::getIsDisplay, 1).ne(Activity::getStatus, 4).orderByDesc(Activity::getRegisteredNumber).last("LIMIT 5"));
        if (!activities.isEmpty()) {
            return activities.stream().map(activity -> {
                HomeDataVO.ActivityVO activityVO = new HomeDataVO.ActivityVO();
                BeanUtils.copyProperties(activity, activityVO);
                activityVO.setStartTime(formatTime(activity.getStartTime()));
                activityVO.setEndTime(formatTime(activity.getEndTime()));
                activityVO.setRegisterStartTime(formatTime(activity.getRegisterStartTime()));
                activityVO.setRegisterEndTime(formatTime(activity.getRegisterEndTime()));
                return activityVO;
            }).collect(Collectors.toList());
        }
        return List.of();
    }

    @Override
    public CompletableFuture<ActivityDetailVO> getActivityDetail(Long activityId, Long userId) {
        return CompletableFuture.supplyAsync(() -> {
            // 查询活动信息
            Activity activity = activityMapper.selectById(activityId);
            if (activity == null) {
                return null;
            }

            ActivityDetailVO detailVO = new ActivityDetailVO();
            BeanUtils.copyProperties(activity, detailVO);

            // 如果用户ID不为空，查询收藏和报名状态
            if (userId != null) {
                // 查询是否已收藏
                LambdaQueryWrapper<UserCollection> collectionQuery = new LambdaQueryWrapper<>();
                collectionQuery.eq(UserCollection::getUserId, userId).eq(UserCollection::getActivityId, activityId);
                Long count = collectionMapper.selectCount(collectionQuery);
                detailVO.setIsCollected(count > 0);

                // 查询报名状态
                LambdaQueryWrapper<Registration> registrationQuery = new LambdaQueryWrapper<>();
                registrationQuery.eq(Registration::getUserId, userId).eq(Registration::getActivityId, activityId);
                Registration registration = registrationMapper.selectOne(registrationQuery);

                if (registration != null) {
                    detailVO.setIsRegistered(true);
                } else {
                    detailVO.setIsRegistered(false);
                }
            }

            return detailVO;
        });
    }

    /**
     * 时间格式化
     *
     * @param time time
     * @return String
     */
    private String formatTime(LocalDateTime time) {
        if (time == null) {
            return "";
        }
        return time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    @Override
    public CompletableFuture<List<ActivityListVO>> getActivityList(Integer status, Boolean isRecommended, Integer page, Integer size) {
        return CompletableFuture.supplyAsync(() -> {
            LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();

            // 筛选条件
            if (status != null) {
                queryWrapper.eq(Activity::getStatus, status);
            }
            if (isRecommended != null) {
                queryWrapper.eq(Activity::getIsRecommended, isRecommended);
            }

            // 只查询显示的活动
            queryWrapper.eq(Activity::getIsDisplay, true);

            // 按创建时间倒序排序
            queryWrapper.orderByDesc(Activity::getCreateTime);

            // 分页查询
            Page<Activity> pageResult = activityMapper.selectPage(new Page<>(page, size), queryWrapper);

            // 转换为VO对象
            List<ActivityListVO> result = pageResult.getRecords().stream().map(activity -> {
                ActivityListVO vo = new ActivityListVO();
                BeanUtils.copyProperties(activity, vo);
                return vo;
            }).collect(Collectors.toList());

            return result;
        });
    }


    @Override
    @Transactional
    public CompletableFuture<Boolean> deleteActivity(Long activityId) {
        return CompletableFuture.supplyAsync(() -> {
            // 逻辑删除，设置is_display为false
            LambdaUpdateWrapper<Activity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Activity::getId, activityId).set(Activity::getIsDisplay, false).set(Activity::getUpdateTime, LocalDateTime.now());

            int result = activityMapper.update(null, updateWrapper);
            return result > 0;
        });
    }

    @Override
    @Transactional
    public CompletableFuture<Boolean> recommendActivity(Long activityId, Boolean isRecommended) {
        return CompletableFuture.supplyAsync(() -> {
            LambdaUpdateWrapper<Activity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Activity::getId, activityId).set(Activity::getIsRecommended, isRecommended).set(Activity::getUpdateTime, LocalDateTime.now());

            int result = activityMapper.update(null, updateWrapper);
            return result > 0;
        });
    }

    @Override
    @Transactional
    public CompletableFuture<Boolean> updateActivityStatus(Long activityId, Integer status) {
        return CompletableFuture.supplyAsync(() -> {
            LambdaUpdateWrapper<Activity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Activity::getId, activityId).set(Activity::getStatus, status).set(Activity::getUpdateTime, LocalDateTime.now());

            int result = activityMapper.update(null, updateWrapper);
            return result > 0;
        });
    }

    @Override
    public CompletableFuture<List<ActivityListVO>> getCreatedActivities(Long userId, Integer page, Integer size) {
        return CompletableFuture.supplyAsync(() -> {
            LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Activity::getCreatorId, userId).eq(Activity::getIsDisplay, true).orderByDesc(Activity::getCreateTime);

            Page<Activity> pageResult = activityMapper.selectPage(new Page<>(page, size), queryWrapper);

            return pageResult.getRecords().stream().map(activity -> {
                ActivityListVO vo = new ActivityListVO();
                BeanUtils.copyProperties(activity, vo);
                return vo;
            }).collect(Collectors.toList());
        });
    }

    @Override
    public CompletableFuture<List<ActivityListVO>> getHotActivities(Integer limit) {
        return CompletableFuture.supplyAsync(() -> {
            LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Activity::getIsDisplay, true).eq(Activity::getIsRecommended, true).orderByDesc(Activity::getRegisteredNumber).last("LIMIT " + limit);

            List<Activity> activities = activityMapper.selectList(queryWrapper);

            return activities.stream().map(activity -> {
                ActivityListVO vo = new ActivityListVO();
                BeanUtils.copyProperties(activity, vo);
                return vo;
            }).collect(Collectors.toList());
        });
    }

    @Override
    public CompletableFuture<Integer> getActivityCount() {
        return CompletableFuture.supplyAsync(() -> {
            LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Activity::getIsDisplay, true);
            return Math.toIntExact(activityMapper.selectCount(queryWrapper));
        });
    }

    @Override
    public CompletableFuture<List<ActivityListVO>> getJoinedActivities(Long userId, Integer page, Integer size) {
        return CompletableFuture.supplyAsync(() -> {
            // 先查询用户报名的活动ID
            LambdaQueryWrapper<Registration> registrationQuery = new LambdaQueryWrapper<>();
            registrationQuery.eq(Registration::getUserId, userId).eq(Registration::getStatus, 1); // 已通过审核的报名

            Page<Registration> registrationPage = registrationMapper.selectPage(new Page<>(page, size), registrationQuery);
            List<Long> activityIds = registrationPage.getRecords().stream().map(Registration::getActivityId).collect(Collectors.toList());

            if (activityIds.isEmpty()) {
                return new ArrayList<>();
            }

            // 查询活动详情
            LambdaQueryWrapper<Activity> activityQuery = new LambdaQueryWrapper<>();
            activityQuery.in(Activity::getId, activityIds).eq(Activity::getIsDisplay, true);

            List<Activity> activities = activityMapper.selectList(activityQuery);

            return activities.stream().map(activity -> {
                ActivityListVO vo = new ActivityListVO();
                BeanUtils.copyProperties(activity, vo);
                return vo;
            }).collect(Collectors.toList());
        });
    }
}
